package com.zjw.touchscreen.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;
import androidx.core.content.FileProvider;
import com.zjw.touchscreen.config.RetrofitManager;
import com.zjw.touchscreen.http.ApiInterface;
import com.zjw.touchscreen.http.HttpStatus;
import com.zjw.touchscreen.http.entity.LastVersionRespVO;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Objects;

public class UpdateUtils {

    public static Integer getVersionCode(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo = null;
        try {
            packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static void update(Activity activity) {
        ApiInterface apiInterface = RetrofitManager.create(ApiInterface.class);
        Call<LastVersionRespVO> lastVersionCall = apiInterface.lastVersion(getVersionCode(activity));
        lastVersionCall.enqueue(new Callback<LastVersionRespVO>() {
            @Override
            public void onResponse(Call<LastVersionRespVO> call, Response<LastVersionRespVO> response) {
                LastVersionRespVO body = response.body();
                if (HttpStatus.SUCCESS != response.code()) {
                    Toast.makeText(activity.getApplicationContext(), "检查更新失败!", Toast.LENGTH_SHORT).show();
                    return;
                }
                LastVersionRespVO.Version data = body.getData();
                if (Objects.isNull(data)) {
                    return;
                }
                Boolean isForce = data.getIsForce();
                String fileName = data.getUrl();

                AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                builder.setTitle("检查更新");
                builder.setMessage("有新版本！");
                builder.setCancelable(false);
                builder.setPositiveButton("更新", null);
                if (!isForce) {
                    builder.setNegativeButton("忽略", (dialog, which) -> {
                        // 执行取消按钮的操作
                    });
                }

                AlertDialog dialog = builder.create();
                dialog.show();
                dialog.getButton(AlertDialog.BUTTON_POSITIVE)
                        .setOnClickListener(v -> {
                            download(activity, dialog, data);
                        });
            }

            @Override
            public void onFailure(Call<LastVersionRespVO> call, Throwable throwable) {
                Toast.makeText(activity.getApplicationContext(), "检查更新失败!", Toast.LENGTH_SHORT).show();
                activity.finish();
            }
        });
    }

    private static void download(Activity activity, AlertDialog dialog, LastVersionRespVO.Version data) {
        long now = System.currentTimeMillis();
        String fileName = data.getUrl();
        ApiInterface apiInterface = RetrofitManager.create(ApiInterface.class);
        Call<ResponseBody> downloadCall = apiInterface.download(fileName, false);
        downloadCall.enqueue(new Callback<ResponseBody>() {

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                new Thread(() -> {
                    ResponseBody body = response.body();
                    if (HttpStatus.SUCCESS != response.code()) {
                        Toast.makeText(activity.getApplicationContext(), "检查更新失败!", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    //文件总长度
                    long totalLength = body.contentLength();
                    File cacheDir = activity.getCacheDir();
                    File file = new File(cacheDir, fileName.substring(fileName.lastIndexOf("/") + 1));
                    FileOutputStream fos = null;
                    boolean success = false;
                    try {
                        fos = new FileOutputStream(file);
                        long length = 0;
                        //本次传输的文件长度
                        int len = -1;
                        byte[] buf = new byte[1024];
                        while (true) {
                            if (System.currentTimeMillis() - now > 1000 * 60 * 5) {
                                Toast.makeText(activity.getApplicationContext(), "下载超时!", Toast.LENGTH_SHORT).show();
                                break;
                            }
                            if (length < totalLength) {
                                len = body.byteStream().read(buf);
                                if (len > 0) {
                                    fos.write(buf, 0, len);
                                    length += len;
                                    float progress = (int) ((((float) length) / totalLength) * 100);
                                    long finalLength = length;
                                    activity.runOnUiThread(() -> dialog.setMessage("已下载：" + progress + "%             " + byteToAuto(finalLength) + "/" + byteToAuto(totalLength)));
                                }
                                continue;
                            }
                            success = true;
                            break;
                        }
                        fos.flush();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    } finally {
                        if (fos != null) {
                            try {
                                fos.close();
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                    if (success) {
                        installApk(activity, file);
                    }
                }).start();
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable throwable) {
                Log.e("onFailure: ", throwable.getMessage());
            }
        });
    }

    private static String byteToAuto(double length) {
        if (length < 1024) {
            return (int) length + "B";
        }
        length = length / 1024;
        if (length < 1024) {
            return (int) length + "KB";
        }
        length = length / 1024;
        if (length < 1024) {
            return (int) length + "MB";
        }
        length = length / 1024;
        if (length < 1024) {
            return (int) length + "GB";
        }
        length = length / 1024;
        if (length < 1024) {
            return (int) length + "TB";
        }
        length = length / 1024;
        if (length < 1024) {
            return (int) length + "PB";
        }
        length = length / 1024;
        return (int) length + "EB";
    }

    /**
     * 安装apk
     */
    protected static void installApk(Activity activity, File file) {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= 24) {
            Uri apkUri = FileProvider.getUriForFile(activity, activity.getApplicationContext().getPackageName() + ".fileProvider", file); //这里要写你程序的包名，已实验不可使用${applicationId}
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        activity.startActivity(intent);
    }
}
